//
//  NetRequest.m
//  CustomHUD
//
//  Created by feiwei on 15/11/23.
//  Copyright © 2015年 feiwei. All rights reserved.
//

#import "NetRequest.h"

@implementation NetRequest
static NetRequest *_instance;
+ (instancetype)shareInstance {
    //    @synchronized (self) {
    //        // 为了防止多线程同时访问对象，造成多次分配内存空间，所以要加上线程锁
    //        if (_instance == nil) {
    //            _instance = [super allocWithZone:zone];
    //        }
    //        return _instance;
    //    }
    // 也可以使用一次性代码
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_instance == nil) {
            _instance = [[super alloc] init];
        }
    });
    return _instance;
}

+ (void)getDataWithUrlString:(NSString *)urlString withParams:(NSDictionary *)params success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:urlString parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failBlock(error.localizedFailureReason);
    }];
}

+ (void)postDataWithUrlString:(NSString *)urlString withParams:(NSDictionary *)params success:(SuccessBlock)successBlock fail:(FailBlock)failBlock refresh:(RefreshBlock)refreshBlock{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 5.0f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [MYFactoryManager showFrameAnimationBubble:nil];
    [NetRequest shareInstance].refreshed = refreshBlock;
    [manager POST:urlString parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [NetRequest shareInstance].contentView.hidden = YES;
        [MYFactoryManager hideBubbleFrame:1.0f];
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MYFactoryManager hideBubbleFrame:0];
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [[NetRequest shareInstance] initView];
//        });
        [[NetRequest shareInstance] initView];
        double delayInSeconds = 0.3;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            failBlock(error.localizedFailureReason);
        });
    }];
}

- (void)refreshControl {
//    _contentView.hidden = YES;
    if (self.refreshed) {
        self.refreshed();
    }
}

- (void)initView {
//    lkbubble1.jpg
    if (_contentView == nil) {
        _contentView = [[UIView alloc] initWithFrame:CGRectZero];
        _contentView.backgroundColor = [UIColor whiteColor];
        [AppDelegateInstance.window addSubview:_contentView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(refreshControl)];
        [_contentView addGestureRecognizer:tap];
        [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing.mas_equalTo(0);
            make.top.mas_equalTo(64);
            make.bottom.mas_equalTo(0);
        }];
        UIButton *button = [UIButton buttonWithFrame:CGRectZero title:nil image:@"refreshing" target:self action:@selector(refreshControl)];
        [_contentView addSubview:button];
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_contentView);
            make.centerY.equalTo(_contentView).offset(-120*boringScale);
            make.size.mas_equalTo(CGSizeMake(100*boringScale, 100*boringScale));
        }];
        UILabel *label = [UILabel labelWithFrame:CGRectZero text:@"网络出错，轻触屏幕重新加载" font:18*boringScale textColor:[UIColor grayColor]];
        [_contentView addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_contentView);
            make.top.equalTo(button.mas_bottom).offset(20*boringScale);
            make.height.mas_equalTo(20*boringScale);
        }];
    }
    [AppDelegateInstance.window insertSubview:_contentView belowSubview:[LKBubbleView defaultBubbleView]];
    _contentView.hidden = NO;
}

@end
